<%#
kind: registration
name: Global Registration
model: ProvisioningTemplate
-%>
#!/bin/sh
<%
    headers = ["-H 'Authorization: Bearer #{@auth_token}'"]
-%>

# Rendered with following template parameters:
<%= "# User: [#{@user.login}]" -%>
<%= "\n# Organization: [#{@organization.name}]" if @organization -%>
<%= "\n# Location: [#{@location.name}]" if @location -%>
<%= "\n# Hostgroup: [#{@hostgroup.name}]" if @hostgroup -%>
<%= "\n# Operating System: [#{@operatingsystem.name}]" if @operatingsystem -%>
<%= "\n# Setup Insights: [#{@setup_insights}]" unless @setup_insights.nil? -%>


if ! [ $(id -u) = 0 ]; then
    echo "Please run as root"
    exit 1
fi

if [ -f /etc/os-release ] ; then
  . /etc/os-release
fi

SSL_CA_CERT=$(mktemp)
cat << EOF > $SSL_CA_CERT
<%= foreman_server_ca_cert %>
EOF


register_host() {
  curl --cacert $SSL_CA_CERT --request POST <%= @registration_url %> \
       <%= headers.join(' ') %> \
       --data "host[name]=$(hostname --fqdn)" \
       --data "host[build]=false" \
       --data "host[managed]=false" \
       <%= "--data \"host[organization_id]=#{@organization.id}\"" if @organization -%>
       <%= "--data \"host[location_id]=#{@location.id}\"" if @location -%>
       <%= "--data \"host[hostgroup_id]=#{@hostgroup.id}\"" if @hostgroup -%>
       <%= "--data \"host[operatingsystem_id]=#{@operatingsystem.id}\"" if @operatingsystem -%>
       <%= "--data \"setup_insights=#{@setup_insights}\"" unless @setup_insights.nil? -%>

}

echo "#"
echo "# Running registration"
echo "#"

<% if plugin_present?('katello') -%>
if [ x$ID = xrhel ] || [ x$ID = xcentos ]; then
    register_katello_host(){
        UUID=$(subscription-manager identity | head -1 | awk '{print $3}')
        curl --cacert $SSL_CA_CERT --request POST "<%= @registration_url %>?uuid=$UUID" \
            <%= headers.join(' ') %> \
            <%= "--data \"host[organization_id]=#{@organization.id}\"" if @organization -%>
            <%= "--data \"host[location_id]=#{@location.id}\"" if @location -%>
            <%= "--data \"host[hostgroup_id]=#{@hostgroup.id}\"" if @hostgroup -%>
            <%= "--data \"setup_insights=#{@setup_insights}\"" unless @setup_insights.nil? -%>

    }

    CONSUMER_RPM=$(mktemp --suffix .rpm)
    curl --output $CONSUMER_RPM <%= subscription_manager_configuration_url(hostname: @url_host) %>
    yum localinstall $CONSUMER_RPM -y
    rm -f $CONSUMER_RPM

    subscription-manager register --org=<%= @organization.label %> --activationkey="<%= @activation_key %>"
    register_katello_host | bash
else
    register_host | bash
fi
<% else -%>
register_host | bash
<% end -%>
